<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click.stop="handleSave"
          >新建</el-button
        >
      </template>
      <template slot-scope="{ row }" slot="activityJson">
        <div>
          <div
            style="margin-bottom: 4px"
            v-for="(item, index) in JSON.parse(row.activityJson)"
            :key="index"
          >
            <el-tag
              >充值满{{ item.rechargeAmount }}赠{{
                item.rewardAmount
              }}元</el-tag
            >
          </div>
        </div>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button
          icon="el-icon-view"
          size="small"
          type="text"
          @click.stop="handleDetail(scope.row, scope.index)"
          >详 情</el-button
        >
        <el-button
          icon="el-icon-edit"
          size="small"
          type="text"
          @click.stop="handleEdit(scope.row, scope.index)"
          >编 辑</el-button
        >
      </template>
    </avue-crud>
    <el-dialog
      class="avue-dialog"
      :title="dialogText + '活动'"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
    >
      <ticket-form
        :inputForm="ticketForm"
        :method="dialogType"
        ref="toticketForm"
      />
      <span slot="footer" class="dialog-footer" v-if="dialogType != 'view'">
        <el-button size="small" @click="handleSubmit" v-preventClick
          >提交</el-button
        >
      </span>
    </el-dialog>
  </basic-container>
</template>
  
    <script>
import {
  getList,
  getStatistics,
  add
} from "@/api/rb-merchant/rpiMemberOem/recharge_activity";
import { mapGetters } from "vuex";
import selectPage from "@/components/select-page/select-page";
import ticketForm from "./components/form/ticket-form";

export default {
  components: {
    selectPage,
    ticketForm
  },
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        selection: true,
        searchMenuSpan: 24,
        columnBtn: false,
        labelWidth: 120, //弹出表单的标题的统一宽度
        searchLabelWidth: 120, //搜索框标题宽度
        menuWidth: 200, //操作栏宽度
        emptyBtnText: "重置",
        menu: true,
        column: [
          {
            label: "会员活动编号",
            searchLabel: "会员活动编号",
            prop: "activityNo",
            type: "input",
            search: true,
            overHidden: true,
            minWidth: 100,
          },
          {
            label: "会员活动名称",
            prop: "activityName",
            type: "input",
            search: true,
            minWidth: 150,
          },
          {
            label: "活动状态",
            prop: "activityStatus",
            type: "select",
            dataType: "string",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            search: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=activity_status",
            minWidth: 150,
          },
          {
            label: "活动类型",
            prop: "activityType",
            type: "select",
            dataType: "string",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            search: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=activity_type",
            minWidth: 150,
          },
          {
            label: "活动范围",
            prop: "activityRange",
            type: "select",
            dataType: "string",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            search: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=activity_range",
            minWidth: 150,
          },
          {
            label: "活动规则",
            prop: "activityJson",
            type: "input",
            overHidden: true,
            minWidth: 150,
          },
          {
            label: "活动有效期",
            prop: "validDate",
            type: "input",
            minWidth: 180,
          },
          {
            label: "活动有效期",
            prop: "validDateArr",
            type: "datetimerange",
            searchRange: true,
            defaultTime: ["00:00:00", "23:59:59"],
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            startPlaceholder: "开始时间",
            endPlaceholder: "结束时间",
            search: true,
            hide: true,
            display: false,
            searchSpan: 12,
            minWidth: 180,
          },
          {
            label: "创建日期",
            prop: "createTime",
            type: "input",
            minWidth: 140,
          },
          {
            label: "创建日期",
            prop: "createDate",
            type: "datetimerange",
            searchRange: true,
            defaultTime: ["00:00:00", "23:59:59"],
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            startPlaceholder: "开始时间",
            endPlaceholder: "结束时间",
            search: true,
            hide: true,
            display: false,
            searchSpan: 12,
            minWidth: 180,
          },
          {
            label: "支付前弹窗状态",
            prop: "isPayShowName",
            type: "input",
            minWidth: 150,
          },
        ],
      },
      data: [],
      dialogVisible: false,
      dialogType: "", //打开类型 add/edit
      dialogText: "",
      ticketForm: {
        activityName: "",
        activityRange: 1,
        activityRangeName: "",
        activityStatus: 1,
        activityStatusName: "",
        activityType: 1,
        activityTypeName: "",
        timeDate: [],
        amountList: [
          {
            rechargeAmount: 0,
            rewardAmount: 0,
          },
        ],
        endDate: "",
        id: "",
        isPayShow: 1,
        rechargeQrImg: "",
        rpiNo: "",
        startDate: "",
      },
    };
  },
  computed: {
    ...mapGetters(["permission", "selectMer"]),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.summaryOfCashback_view, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    exhibition() {
      return (val) => {
        if (val == "" || val == "-1") {
          return (val = 0);
        } else {
          return val;
        }
      };
    },
  },
  methods: {
    handleSubmit() {
      this.$refs["toticketForm"].$refs["inputForm"].validate((valid) => {
        console.log(valid, 'valid');
        if (valid) {
          // this.ticketForm.giveType = this.ticketForm.giveType.join(",");
        add(Object.assign(this.ticketForm, { rpiNo: this.selectMer.rpiNo })).then(
            (res) => {
              this.dialogVisible = false;
              this.searchReset();
              if (res.data.code == "200") {
                this.$message({
                  type: "success",
                  message: "操作成功!",
                });
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message,
                });
              }
            },
            (error) => {
              window.console.log(error);
            }
          );
        } else {
          return false;
        }
      });
    },
    /**
     * @func 新增
     * @desc 点击新增初始化显示基本信息
     * */
    handleSave() {
      this.dialogVisible = true;
      this.dialogType = "add";
      this.dialogText = "新增";
      this.ticketForm.id = null;
      this.$nextTick(() => {
        this.ticketForm = {
          activityName: "",
          activityRange: 1,
          activityRangeName: "",
          activityStatus: 1,
          activityStatusName: "",
          activityType: 1,
          activityTypeName: "",
          timeDate: [],
          amountList: [
            {
              rechargeAmount: 0,
              rewardAmount: 0,
            },
          ],
          endDate: "",
          id: "",
          isPayShow: 1,
          rechargeQrImg: "",
          rpiNo: "",
          startDate: "",
        };
        this.$refs["toticketForm"].isTicketType = true;
      });
    },
    /**
     * @func 详情
     * @desc 点击详情进入详情界面
     * @param {Object} row - 商户信息
     * */
    handleDetail(row) {
      this.dialogType = "view";
      this.dialogText = "详情";
      getStatistics({ id: row.id }).then((res) => {
        let data = res.data.data;
        this.dialogVisible = true;
        if (data.startDate && data.endDate) {
          this.$set(data, "timeDate", [data.startDate, data.endDate]);
        }
        this.$nextTick(() => {
          this.ticketForm = data;
          this.$refs["toticketForm"].isTicketType = true;
        });
      });
    },
    handleEdit(row) {
      this.dialogType = "edit";
      this.dialogText = "编辑";
      getStatistics({ id: row.id }).then((res) => {
        let data = res.data.data;
        this.dialogVisible = true;
        if (data.startDate && data.endDate) {
          this.$set(data, "timeDate", [data.startDate, data.endDate]);
        }
        this.$nextTick(() => {
          this.ticketForm = data;
          this.$refs["toticketForm"].isTicketType = true;
        });
      });
    },
    /**
     * @func edit,view 打开之前回调
     * @desc 点击获取点击天数时间
     * */
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getStatistics(this.form.id).then(res => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    /**
     * @func 重置
     * @desc 重置查询条件
     * */
    searchReset() {
      this.query = {};
      this.search = {};
      this.onLoad(this.page);
    },
    /**
     * @func 搜索
     * @desc 根据条件查询
     * @param {params} params --- 条件查询
     * */
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    /**
     * @func 选中单元格
     * @desc 选中单元格数据
     * @param {list} list --- 选中单元格数据-数组
     * */
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * @func 分页页码
     * @desc 分页页码改变时会触发
     * */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      // this.refreshChange();
      this.onLoad(this.page, this.query);
    },
    /**
     * @func 当前页个数
     * @desc pageSize改变时会触发
     * */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      // this.refreshChange();
      this.onLoad(this.page, this.query);
    },
    /**
     * @func 刷新
     * @desc 点击刷新按钮触发该事件
     * */
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    /**
     * @func 初始化
     * @desc 表格初始化查询数据
     * */
    onLoad(page, params = {}) {
      this.loading = true;
      let paramObj = Object.assign(params, this.query);
      if (!this.validatenull(paramObj.createDate)) {
        paramObj.beginTime = paramObj.createDate[0] || "";
        paramObj.endTime = paramObj.createDate[1] || "";
      }
      delete paramObj.createDate;
      if (!this.validatenull(paramObj.validDateArr)) {
        paramObj.begin = paramObj.validDateArr[0] || "";
        paramObj.end = paramObj.validDateArr[1] || "";
      }
      delete paramObj.validDateArr;

      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(paramObj, { rpiNo: this.selectMer.rpiNo })
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    /**
     * @func 导出
     * @desc 根据条件导出
     * */
    handleExport() {
      let paramObj = this.query;
      if (!this.validatenull(paramObj.createDate)) {
        paramObj.beginTime = paramObj.createDate[0] || "";
        paramObj.endTime = paramObj.createDate[1] || "";
      }
      delete paramObj.createDate;

      if (!this.validatenull(paramObj.validDateArr)) {
        paramObj.begin = paramObj.validDateArr[0] || "";
        paramObj.end = paramObj.validDateArr[1] || "";
      }
      delete paramObj.validDateArr;

      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        getExport(paramObj).then(
          (res) => {
            downloadFileExcel(res);
          },
          (error) => {
            window.console.log(error);
          }
        );
      });
    },
    /**
     * @func 排序
     * @desc 根据表格字段排序
     * */
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  },
};
</script>
  
    <style lang="scss" scoped>
.curd-foter {
  padding-top: 10px;
  display: flex;
  flex-wrap: wrap;
}

.redFontBox {
  margin-right: 40px;
  .redFont {
    color: red;
  }
}
/deep/ .el-tag--dark.el-tag--success {
  border: none !important;
}
</style>
  